package com.laot.search.controller;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.laot.search.baiduChat.BaiduEventSourceListener;
import com.laot.search.baiduChat.BaiduService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.laot.baiduAi.BaiduChatMessage;
import org.laot.baiduAi.ErnieBotTurboStreamParam;
import org.laot.seacher_master.model.common.BaseResponse;
import org.laot.seacher_master.model.common.ErrorCode;
import org.laot.seacher_master.model.common.ResultUtils;
import org.laot.seacher_master.model.exception.BusinessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "文心一言接口")
@RestController
@RequestMapping("/baidu/chat")
public class BaiduChatController {

    @Resource
    private BaiduService baiduService;
    @Resource
    private RedisTemplate redisTemplate;

    private static String BAIDU_PIX = "baidu:";


    @ApiOperation("调用文心一言")
    @GetMapping("/use")
    public SseEmitter useAi(String id, HttpServletResponse response){
        String s = (String) redisTemplate.opsForValue().get(BAIDU_PIX + id);
        if(StringUtils.isBlank(s)) throw new BusinessException(ErrorCode.OPERATION_ERROR,"当前请求不存在!");
        //根据id获取对应信息
        List<BaiduChatMessage> messages = JSONUtil.toList(s, BaiduChatMessage.class);
        SseEmitter emitter = new SseEmitter();
        ErnieBotTurboStreamParam param = new ErnieBotTurboStreamParam();
        //填充基本信息
        param.setStream(false);
        param.setMessages(messages);
        baiduService.ernieBotTurboStream(param,new BaiduEventSourceListener(response,emitter));
        return emitter;
    }

    @PostMapping("/getId")
    @ApiOperation("获取文心一言专属id")
    public BaseResponse<String> getId(@RequestBody List<BaiduChatMessage> messages){
        //获取当前时间撮
        long currentDate = System.currentTimeMillis();
        //获取3个随机数
        int randomInt = RandomUtil.randomInt(4);
        //生成唯一的id
        String key = currentDate+"_"+randomInt;
        //保存到Redis
        redisTemplate.opsForValue().set(BAIDU_PIX+key, JSONUtil.toJsonStr(messages),1, TimeUnit.MINUTES);
        return ResultUtils.success(key);
    }

}
